document.addEventListener('DOMContentLoaded', function () {
  app.initPage();
});

function loadPage() {
  setTimeout(() => {
    isTeaLogin();
  }, 200);
  loadStudentForm();
  $.get(`${app.urlLocation.queryAllStu}/${app.pageHelper.global_page}/${app.pageHelper.global_limit}`, student => {
    if (student.data.length === 0 && app.pageHelper.global_page > 1) {
      app.pageHelper.global_page--;
      loadPage();
    } else {
      loadStudentTable(student);
      loadStudentPage(student);
    }
  })
}

function loadStudentTable(student) {
  layui.use(['table', 'layer'], () => {
    let table = layui.table,
        layer = layui.layer;
    table.render({
      elem: '#student',
      data: student.data,
      toolbar: '#student-toolbar',
      limit: student.limit,
      cols: [
        [
          {type: 'checkbox'},
          {field: 'studentNo', title: '学生学号'},
          {field: 'name', title: '学生姓名'},
          {
            field: 'gender', title: '性别', templet: d => {
              return d.gender === 0 ? '男' : '女';
            }
          },
          {field: 'age', title: '年龄(岁)'},
          {field: 'email', title: '邮箱'},
          {field: 'phone', title: '手机号'},
          {
            field: 'createTime', title: '录入时间', templet: d => {
              return app.formatDate(new Date(d.createdTime));
            }
          },
          {title: '操作', toolbar: '#student-tool'}
        ]
      ]
    });
    table.on('toolbar(student)', obj => {
      switch (obj.event) {
        case 'add':
          $('.layout .layout-title').text('录入学生信息');
          $('.layout button:eq(0)').text('录入').attr('lay-filter', 'add');
          showLayout($('.layout'));
          break;
        case 'del':
          layer.confirm('删除将不可恢复，是否删除?', {
            btn: ['删除', '不删除']
          }, () => {
            let data = table.checkStatus(obj.config.id).data,
                ids = [];
            $.each(data, (i, v) => {
              ids[i] = v.id;
            });
            ids = JSON.stringify(ids);
            ids = ids.substring(2, ids.length - 2);
            $.post(`${app.urlLocation.deleteStudent}`, {id: ids}, res => {
              if (res === 200)
                layer.msg('已删除选中学生信息');
              else
                layer.msg('学生信息删除失败');
              loadPage();
            });
          });
          break;
      }
    });
    table.on('tool(student)', obj => {
      let event = obj.event,
          data = obj.data;
      switch (event) {
        case 'edit':
          $('.layout input[name=id]').val(data.id);
          $('.layout input[name=studentNo]').val(data.studentNo);
          $('.layout input[name=name]').val(data.name);
          $('.layout input[name=age]').val(data.age);
          $('.layout input[name=phone]').val(data.phone);
          $('.layout input[name=email]').val(data.email);
          $('.layout select[name=gender] option').eq(data.gender).attr('selected', 'selected');
          $('.layout .layout-title').text('修改学生信息');
          $('.layout button:eq(0)').text('修改').attr('lay-filter', 'edit');
          app.resetForm();
          showLayout($('.layout'));
          break;
        case 'del':
          layer.confirm('删除将不可恢复，是否删除?', {
            btn: ['删除', '不删除']
          }, () => {
            $.post(`${app.urlLocation.deleteStudent}`, {id: data.id}, res => {
              if (res === 200)
                layer.msg('学生信息删除成功');
              else
                layer.msg('学生信息删除失败');
              loadPage();
            })
          });
          break;
      }
    });
  })
}

function loadStudentPage(student) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'student-page',
      curr: app.pageHelper.global_page,
      count: student.count,
      limit: app.pageHelper.global_limit,
      limits: [10, 20, 30, 40, 50],
      layout: ['count', 'prev', 'page', 'next', 'limit'],
      jump: function (obj, first) {
        if (!first) {
          app.pageHelper.global_page = obj.curr;
          app.pageHelper.global_limit = obj.limit;
          loadPage();
        }
      }
    });
  })
}

function loadStudentForm() {
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
        layer = layui.layer;
    form.on('submit(add)', obj => {
      let field = obj.field;
      if (field.age < 0 || field.age > 100) {
        layer.msg('年龄不符合规范，请输入0-100之内的数');
      } else {
        $.get(`${app.urlLocation.queryByNo}`, {studentNo: field.studentNo}, result => {
          if (result === '') {
            $.post(`${app.urlLocation.addStudent}`, field, res => {
              res = res === 200 ? '学生信息录入成功' : '学生信息录入失败';
              layer.msg(res);
              hideLayout($('.layout'));
              loadPage();
            })
          } else {
            layer.msg('该学生信息已存在，请勿重复添加');
          }
        })
      }
    });
    form.on('submit(edit)', obj => {
      let field = obj.field;
      if (field.age < 0 || field.age > 100) {
        layer.msg('年龄不符合规范，请输入0-100之内的数');
      } else {
        $.post(`${app.urlLocation.updateStudent}`, field, res => {
          res = res === 200 ? '学生信息修改成功' : '学生信息修改失败';
          layer.msg(res);
          hideLayout($('.layout'));
          loadPage();
        })
      }
    });
  })
}

$('input[name=age]').keyup(function () {
  let reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
  if (reg.test(this.value)) {
    this.value = '';
  } else {
    if (!this.value.match(/^\d*?$/))
      this.value = this.value.substring(0, this.value.length - 1);
  }
});
